<template>
  <div class="enterprise-container">
    <div class="search">
      <el-form :inline="true">
        <el-form-item label="企业名称">
          <el-input v-model="query.name" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" size="medium" @click="$router.push('/parking/enterprise/add')">添加企业</el-button>
    </div>
    <el-table :data="enterpriseList" @expand-change="expandHandle">
      <el-table-column type="expand">
        <template #default="{row}">
          <el-table :data="row.rentList">
            <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
            <el-table-column label="租赁起始时间" prop="startTime" />
            <el-table-column label="合同状态" prop="status" />
            <el-table-column label="操作" width="180">
              <template>
                <el-button size="mini" type="text">续租</el-button>
                <el-button size="mini" type="text">退租</el-button>
                <el-button size="mini" type="text">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号" />
      <el-table-column prop="name" label="企业名称" />
      <el-table-column prop="contact" label="联系人" />
      <el-table-column prop="contactNumber" label="联系电话" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button type="text" size="mini" @click="addRent(scope.row.id)">添加合同</el-button>
          <el-button type="text" size="mini">查看</el-button>
          <el-button type="text" size="mini" @click="edit(scope.row.id)">编辑</el-button>
          <el-button type="text" size="mini" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: right;"
      :current-page="query.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog class="addDialog" title="添加合同" :visible="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="rentForm" label-position="top" :model="rentForm" :rules="rentRules">
          <el-form-item prop="buildingId" label="租赁楼宇">
            <el-select v-model="rentForm.buildingId" style="width:350px">
              <el-option
                v-for="item in rentBuidingList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="rentTime" label="租赁起止日期">
            <el-date-picker
              v-model="rentForm.rentTime"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              style="width:350px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="租赁合同" style="width:350px" prop="contractId">
            <el-upload
              action="#"
              :http-request="uploadFile"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { getEnterpriseListAPI, delEnterpriseAPI, getRentBuildingAPI, addContractAPI, getRentListAPI } from '@/apis/enterprise'
import { uploadAPI } from '@/apis/common'
export default {
  name: 'Building',
  data() {
    return {
      query: {
        name: '',
        page: 1,
        pageSize: 10
      },
      enterpriseList: [],
      total: 0,
      rentDialogVisible: false,
      rentBuidingList: [], // 可租赁楼宇列表
      rentForm: {
        buildingId: '',
        rentTime: [],
        contractUrl: '',
        contractId: '',
        type: 0,
        enterpriseId: ''
      }, // 添加合同信息
      rentRules: {
        buildingId: [{ required: true, message: '请选择租赁楼宇', trigger: 'change' }],
        rentTime: [{ required: true, message: '请选择起止时间', trigger: 'blur' }],
        contractId: [{ required: true, message: '请上传租赁合同', trigger: 'blur' }]
      }, // 添加合同校验规则
      fileList: []
    }
  },
  created() {
    this.getEnterpriseList()
  },
  methods: {
    // 确认添加合同
    confirmAdd() {
      this.$refs.rentForm.validate(async(valid) => {
        if (valid) {
          this.rentForm.startTime = this.rentForm.rentTime[0]
          this.rentForm.endTime = this.rentForm.rentTime[1]
          delete this.rentForm.rentTime
          await addContractAPI(this.rentForm)
          this.$message.success('成功添加合同')
          this.closeDialog()
          this.rentForm = {}
        }
      })
    },
    // 查询可租赁楼宇
    async getRentBuilding() {
      const res = await getRentBuildingAPI()
      this.rentBuidingList = res.data
    },
    // 上传租赁合同
    async uploadFile(data) {
      const file = data.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')
      const res = await uploadAPI(formData)
      this.rentForm.contractUrl = res.data.url
      this.rentForm.contractId = res.data.id
    },
    // 添加合同
    addRent(id) {
      this.rentDialogVisible = true
      this.getRentBuilding()
      this.rentForm.enterpriseId = id
    },
    // 关闭
    closeDialog() {
      this.rentDialogVisible = false
    },
    // 删除企业
    del(id) {
      this.$confirm('是否确定删除该企业?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        await delEnterpriseAPI(id)
        this.$message.success('删除成功')
        this.getEnterpriseList()
      })
    },
    // 跳转编辑
    edit(id) {
      this.$router.push({
        name: 'addEnterprise',
        query: {
          id
        }
      })
    },
    // 查询
    search() {
      this.query.page = 1
      this.getEnterpriseList()
    },
    // 获取企业列表
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.query)
      this.enterpriseList = res.data.rows.map((item) => {
        return {
          ...item,
          rentList: [] // 每一行补充存放合同的列表
        }
      })
      this.total = res.data.total
    },
    // 只有展开时获取数据并绑定
    // row: 当前展开那行表格的数据对象
    // rows：当前已展开的所有行表格的数据对象的集合
    async expandHandle(row, rows) {
      // rows 中包含当前展开行数据，说明是展开状态
      const isExpend = rows.find(item => item.id === row.id)
      // 因为展开/关闭都会触发此事件函数，做个判断只有展开时获取数据
      if (isExpend) {
        const res = await getRentListAPI(row.id)
        res.data.forEach(obj => {
          row.rentList.push(obj)
        })
      } else {
        // 关闭时，把当前行的合同列表清空，防止下次打开时不断 push 叠加
        row.rentList.splice(0)
      }
    },
    // 分页方法
    handleSizeChange(pageSize) {
      this.query.pageSize = pageSize
      this.getEnterpriseList()
    },
    handleCurrentChange(page) {
      // 把点击的页数赋值给请求参数页数
      this.query.page = page
      // 使用最新的请求参数获取列表数据
      this.getEnterpriseList()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  display: flex;
  justify-content: center;
}

</style>
